﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Description;
using System.ServiceModel;
using Microsoft.Practices.Unity;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Channels;
using System.Collections;

namespace Infrastructure.Aspect.Extensions
{
    public class UnityServiceBehavior : IServiceBehavior    
   {        
       public UnityInstanceProvider InstanceProvider { get; set; }        
       private ServiceHost serviceHost = null;    
       public UnityServiceBehavior()        
       {            
           InstanceProvider = new UnityInstanceProvider();        
       }        
       public UnityServiceBehavior(IUnityContainer unity)        
       {            
           InstanceProvider = new UnityInstanceProvider();            
           InstanceProvider.Container = unity;        
       }        
       public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase) 
       {            
           foreach (ChannelDispatcherBase cdb in serviceHostBase.ChannelDispatchers)   
           {                
               ChannelDispatcher cd = cdb as ChannelDispatcher;                
               if (cd != null)                
               {                    
                   foreach (EndpointDispatcher ed in cd.Endpoints)                    
                   {                        
                       InstanceProvider.ServiceType = serviceDescription.ServiceType;
                       ed.DispatchRuntime.InstanceProvider  = InstanceProvider;
                   //    ed.DispatchRuntime.InstanceContextProvider = new UnityInstanceContextProvider();
                   }                
               }            
           }        
       }        
       
       public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase) 
       { 

       }        
       public void AddToHost(ServiceHost host)        
       {            
           // only add to host once            
           if (serviceHost != null) return;            
           host.Description.Behaviors.Add(this);            
           serviceHost = host;        
       }

       public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
       {
       
       }
   }
}
